<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总共:{{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'export_excel'" type="warning" size="small" @click="$router.push('/employees/import')">导入excel</el-button>
          <el-button v-allow="'import_excel'" type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style=" margin: 10px; ">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <!-- <img :src="row.staffPhoto" alt="" class="userImg"> -->
              <image-holder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployent(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button v-allow="'allocation_role'" type="text" @click="hAssing(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      width="45%"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <emp-dialog @close="showDialog=false" @success="hSuccess" />
    </el-dialog>

    <el-dialog
      title="分配角色"
      width="45%"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="$refs.assignRole.resetIds()"
    >
      <assing-role :id="curId" ref="assignRole" @close="showDialogRole = false" />
    </el-dialog>
  </div>
</template>
<script>
import { delEmployee, getEmployees } from '@/api/employees'
import employentConst from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssingRole from './assignRole.vue'
import dayjs from 'dayjs'

const hireTypeMap = {}
employentConst.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: { empDialog, AssingRole },
  data() {
    return {
      employees: [],
      q: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      showDialogRole: false,
      curId: '',
      hireType: []
    }
  },
  created() {
    this.loadEmployees()
    // const hireTypeMap = {}
    // employentConst.hireType.forEach(item => {
    //   this.hireTypeMap[item.id] = item.value
    // })
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.total = res.data.total
      this.employees = res.data.rows
    },
    formatEmployent(code) {
      // console.log(code)
      // 去常量中找到对应的中文并返回
      // const result = employentConst.hireType.find(item => item.id === code)
      // // return result.value
      // // 提高代码的健壮性
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return hireTypeMap[code]
    },
    // 分页条数
    hSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    // 分页页数
    hCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    // 删除按钮
    async hDel(id) {
      try {
        // const result = await this.$confirm('真的要删除吗?嘤嘤嘤!!!', '提示', { type: 'warning' }).catch(e => e)
        // if (!result === 'confirm') return
        // 提醒用户
        await this.$confirm('真的要删除吗?嘤嘤嘤!!!', '提示', { type: 'warning' })
        // 发请求
        const res = await delEmployee(id)
        // 提醒用户
        this.$message.success(res.message)
        // 判断: 当前是否为最后一条数据, 并且当前页 > 1, 需要 -1
        if (this.employees.length === 1 && this.q.page > 1) this.q.page--
        // 更新列表
        this.loadEmployees()
      } catch (e) {
        console.log(e)
        // 精细化处理异常
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 发请求获取所有的数据
      const res = await getEmployees({ page: 1, size: this.total })
      // console.log(res)
      const list = res.data.rows

      // 遍历 list 找到每个元素, 将其属性名转为中文
      // const zhList = list.map(enObj => {
      //   const zhObj = {}
      //   const enKeys = Object.keys(enObj)
      //   enKeys.forEach(enKey => {
      //     const zhKey = mapInfo[enKey]
      //     zhObj[zhKey] = enObj[enKey]
      //   })
      //   return zhObj
      // })

      // 取第一个数据
      // const first = zhList[0]
      const first = list[0]
      if (!first) return
      // 取出 header
      const header = Object.keys(first).map(enKey => mapInfo[enKey])

      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })

      // 2. 导出 Excel (表头英文转中文)
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header, // 表头, 传入一个数组
        data, // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
        filename: '员工数据', // 导出的文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })

      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: ['姓名', '职业'], // 表头, 传入一个数组
      //     data: [['黄陂威子', '推拿师'], ['刘谦', '魔术师'], ['刘狄威', 'Tony师傅']], // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
      //     filename: '黄陂在逃人员', // 导出的文件名称
      //     autoWidth: true, // 自适应宽度
      //     bookType: 'xlsx' // 文件类型
      //   })
      // })
    },

    // 分配角色
    hAssing(id) {
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        // 调用子组件的 loadRoleIds 方法, 加载数据
        this.$refs.assignRole.loadrolesId()
      })
    }
  }
}
// hCloseDialog() {
//   this.$refs.AddEmployee.resetForm()
// }
</script>
<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
.el-pagination{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}
.userImg{
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
</style>
